﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using WpfApp3.Models;
using WpfApp3.ViewModels;

namespace WpfApp3.Data
{
    public class Fileoperations
    {
        private readonly string _filePath;
        //方法实现了传入对应文件路径,各实例独立控制文件，和文件的初始化
        // 创建两个操作不同文件的实例
        //var fileOps1 = new Filoperations(@"C:\Data\file1.txt");
        // var fileOps2 = new Filoperations(@"D:\Backup\file2.txt");
        // 两个实例完全独立
        // fileOps1 操作 C:\Data\file1.txt
        // fileOps2 操作 D:\Backup\file2.txt
        public Fileoperations(string filePath)
        {
            _filePath = filePath;  //获取文件目录
            string directory = Path.GetDirectoryName(_filePath);
            // 确保文件目录存在
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            // 确保文件存在
            if (!File.Exists(_filePath))
            {
                File.WriteAllText(_filePath, string.Empty);
            }

        }
        // 添加数据到文件（追加模式）
        public void AddData(string data)
        {
            if (string.IsNullOrEmpty(data))
                throw new ArgumentNullException(nameof(data), "添加的数据不能为空");
            try
            {                  //操作文件     //数据         //Environment.NewLine 用于添加一个换行符
                File.AppendAllText(_filePath, data + Environment.NewLine);
               
            }
            catch (Exception ex)
            {
                MessageBox.Show($"txt文本添加数据失败: {ex.Message}");
                throw;
            }
        }
        public Person ParsePerson(string input)
        {
            // 按空格分割字符串，允许转义空格 (\ )
            var parts = Regex.Split(input, @"(?<!\\)\s+")
                .Select(p => p.Trim().Replace(@"\ ", " "))
                .ToArray();

            string name = parts.Length > 0 ? parts[0] : string.Empty;
            int age = parts.Length > 1 ? (int.TryParse(parts[1], out int parsedAge) ? parsedAge : 0) : 0;
            string gender = parts.Length > 2 ? parts[2] : string.Empty;
            string characteristics = parts.Length > 3 ? parts[3] : string.Empty;
            string political = parts.Length > 4 ? parts[4] : string.Empty;
            string marital = parts.Length > 5 ? parts[5] : string.Empty;
            string remarks = parts.Length > 6 ? parts[6] : string.Empty;

            return new Person
            {
                Name = name,
                Age = age,
                Gender = gender,
                Characteristics = characteristics,
                Marital = marital,
                Political = political,
                Remarks = remarks
            };
        }
        public List<Person> GetAll()
        { 
            var persons = new List<Person>();
            try
            {
               

                // 使用流式读取处理大文件
                using (var reader = new StreamReader(_filePath))
                {
                    string line;
                    int lineNumber = 0;

                    while ((line = reader.ReadLine()) != null)
                    {
                        lineNumber++;

                        // 跳过空行
                        if (string.IsNullOrWhiteSpace(line))
                            continue;

                        try
                        {
                            var newPerson = ParsePerson(line);
                            persons.Add(newPerson);
                        }
                        catch { }
                    }
                }
            }
            catch (IOException ex)
            {
                MessageBox.Show($"读取文件时发生IO错误: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取数据时发生未知错误: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }

            return persons;
        }
        public bool DeletePerson(Person person)
        {
            var allPersons = GetAll();
            try
            {
                allPersons.Remove(person);
                
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除记录失败: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }
        public void UpdatePerson(Person person)
        {
            DeletePerson(person);
            MessageBox.Show("旧数据已在文件中删除");
            AddData($"{person.Name} {person.Age} {person.Gender} {person.Characteristics} {person.Political} {person.Marital} {person.Remarks}");
            MessageBox.Show("新数据已在文件中添加，更新完成");
        }
        public void ClearAll()
        {
            try
            {
                File.WriteAllText(_filePath, string.Empty); // 直接将空字符串写入文件以清空内容
            }
            catch (Exception ex)
            {
                MessageBox.Show($"清空文件失败: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                throw; // 重新抛出异常，让调用者知道操作失败
            }
        }
    }
        
    
    
}
